{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 循环神经网络RNN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From <ipython-input-5-3fd169da6ae6>:38: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See tf.nn.softmax_cross_entropy_with_logits_v2.\n",
      "\n",
      "Iter 0, Testing Accuracy= 0.7178\n",
      "Iter 1, Testing Accuracy= 0.8008\n",
      "Iter 2, Testing Accuracy= 0.8245\n",
      "Iter 3, Testing Accuracy= 0.836\n",
      "Iter 4, Testing Accuracy= 0.8935\n",
      "Iter 5, Testing Accuracy= 0.9119\n"
     ]
    }
   ],
   "source": [
    "#载入数据集\n",
    "mnist = input_data.read_data_sets(\"MNIST_data/\",one_hot=True)\n",
    "\n",
    "# 输入图片是28*28\n",
    "n_inputs = 28 #输入一行，一行有28个数据\n",
    "max_time = 28 #一共28行\n",
    "lstm_size = 100 #隐层单元\n",
    "n_classes = 10 # 10个分类\n",
    "batch_size = 50 #每批次50个样本\n",
    "n_batch = mnist.train.num_examples // batch_size #计算一共有多少个批次\n",
    "\n",
    "#这里的none表示第一个维度可以是任意的长度\n",
    "x = tf.placeholder(tf.float32,[None,784])\n",
    "#正确的标签\n",
    "y = tf.placeholder(tf.float32,[None,10])\n",
    "\n",
    "#初始化权值\n",
    "weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev=0.1))\n",
    "#初始化偏置值\n",
    "biases = tf.Variable(tf.constant(0.1, shape=[n_classes]))\n",
    "\n",
    "#定义RNN网络\n",
    "def RNN(X,weights,biases):\n",
    "    # inputs=[batch_size, max_time, n_inputs]\n",
    "    inputs = tf.reshape(X,[-1,max_time,n_inputs])\n",
    "    #定义LSTM基本CELL\n",
    "    # 下面这行似乎是不用了\n",
    "    # lstm_cell = tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(lstm_size)\n",
    "    lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(lstm_size)\n",
    "    # final_state[0]是cell state\n",
    "    # final_state[1]是hidden_state\n",
    "    outputs,final_state = tf.nn.dynamic_rnn(lstm_cell,inputs,dtype=tf.float32)\n",
    "    results = tf.nn.softmax(tf.matmul(final_state[1],weights) + biases)\n",
    "    return results\n",
    "\n",
    "#计算RNN的返回结果\n",
    "prediction= RNN(x, weights, biases)  \n",
    "#损失函数\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))\n",
    "#使用AdamOptimizer进行优化\n",
    "train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n",
    "#结果存放在一个布尔型列表中\n",
    "correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置\n",
    "#求准确率\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#把correct_prediction变为float32类型\n",
    "#初始化\n",
    "init = tf.global_variables_initializer()\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    for epoch in range(6):\n",
    "        for batch in range(n_batch):\n",
    "            batch_xs,batch_ys =  mnist.train.next_batch(batch_size)\n",
    "            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})\n",
    "        \n",
    "        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\n",
    "        print (\"Iter \" + str(epoch) + \", Testing Accuracy= \" + str(acc))\n",
    "print('completed')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
